<?php

class Empeval_Methods_Request_SetKpiData {
	
	/**
	 *
	 * @var App_Methods_Data_App
	 */
	public $app;
	public $kpiId;
	public $values;
	
	public function __construct($params) {
		$this->app = new App_Methods_Data_App($params->app);
		$this->kpiId = $params->kpiId;
		$this->values = $params->getDefault('values');
	}
	
	public function process() {
		$kpi = EmpevalKpiQuery::create()
		->filterById($this->kpiId)
		->useBonusGoalsFormsQuery()
			->filterByEditorId(Empeval_Auth::getInstance()->getUser()->getId())
		->endUse()
		->findOne();
		
		if (!($kpi instanceof EmpevalKpi))
			throw new Empeval_Exception_App(Empeval_Exception_Codes::INFO_ACCESS_DENIED);
		
		$response = new Empeval_Methods_Response_SetKpiData(true);
		$con = Propel::getConnection('vgp_empeval');
		$con->beginTransaction();
		try {
			foreach ($this->values as $value) {
				if ($value['field'] == 'weight') {
					$value['value'] = (int)$value['value'];
					if ($value['value'] < 10 || $value['value'] > 100) {
						$value['value'] = 10;
					}
				}
				switch ($value['field']) {
					case 'weight':
						$kpi->setWeight($value['value']);
						$response->result = $kpi->getResult();
						$response->weightResult = $kpi->getWeightResult();
						break;
					case 'resultAchieved':
						$kpi->setResultAchieved($value['value']);
						$response->result = $kpi->getResult();
						$response->weightResult = $kpi->getWeightResult();
						break;
					default:
						$kpi->setByName($value['field'], $value['value'], BasePeer::TYPE_STUDLYPHPNAME);
						break;
				}
				$kpi->save($con);
			}
			$con->commit();
		} catch (Exception $e) {
			$con->rollBack();
			throw $e;
		}
		$response->values = $this->values;
		return $response;
	}
	
}